//
//  WBNetworkingManager.swift
//  daoge_sineweibo
//
//  Created by 伍禄林 on 16/9/28.
//  Copyright © 2016年 伍禄林. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMethod {
    case GET
    case POST
}

class WBNetworkingManager: AFHTTPSessionManager {
    //单例的写法
    static let shared: WBNetworkingManager = {
        
        let instance = WBNetworkingManager()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
        
    }()
    
//    var asseccToken: String? //= "2.004FX32G07nppS377571b95d6RQ38D"
//    
//    var uid: String?
    
    lazy var userAccount = WBUserAccount();
    
    var userLogon: Bool {
        
        return userAccount.access_token != nil
    }
    
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String,parameters: Any?,completion: @escaping (_ jsonObjct: Any?,_ isSuccess: Bool) -> ())  {
        
        
        guard let token = userAccount.access_token else {
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            
            completion(nil, false)
            return
            
        }
        
        var parameters = parameters as? [String: Any]
        
        if parameters == nil {
            parameters = [String: Any]()
            
        }
        
        parameters?["access_token"] = token
        
        request(URLString: URLString, parameters: parameters, completion: completion)
        
    }
    
    
    /// 封装 GET ／ POST 请求方法
    ///
    /// - parameter method:     GET ／ POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 请求参数字典
    /// - parameter completion: 完成回调 
    func request(method: WBHTTPMethod = .GET, URLString: String,parameters: Any?,completion: @escaping (_ jsonObjct: Any?,_ isSuccess: Bool) -> ()) {
        
        
        let success = {(task: URLSessionDataTask, data: Any?) in
            completion(data, true)
        }
        
        let failure = { (task: URLSessionDataTask?, error: Error) in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                
                
                print("token 过期了！！！！")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad token")

                
            }
            print("网络请求错误\(error)")
            completion(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
}
